package thread;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-04-11
 * Time: 21:08
 */
class MyBlockingQueue {
    //保存数据本体
    private int[] data = new int[1000];
    //有效元素个数
    private int size = 0;
    //队首下标
    private int head = 0;
    //队尾下标
    private int tail = 0;
    //专门的锁对象
    private Object locker = new Object();


    //入队列,对于put来讲阻塞的条件是队列为满,当take出去一个时,又会重新唤醒
    public void put(int value) throws InterruptedException {
        synchronized (locker) {
            if(size == data.length) {
                //队列满
                //return;
                locker.wait();
            }
            data[tail] = value;
            tail++;
            if(tail >= data.length) {
                tail = 0;
            }
            size++;
            //如果入队列成功,则队列非空,唤醒take中的等待
            locker.notify();
        }

    }
    //出队列,对于take来讲,阻塞条件是队列为空,当put一个时,又会被唤醒
    public Integer take() throws InterruptedException {
        synchronized (locker) {
            if(size == 0) {
                //return null;
                locker.wait();
            }
            int ret = data[head];
            head++;
            if(head >= data.length) {
                head = 0;
            }
            size--;
            //take成功之后,就唤醒put中的等待
            locker.notify();
            return ret;
        }
    }
}
public class Demo13 {
    private static MyBlockingQueue queue = new MyBlockingQueue();

    public static void main(String[] args) {
        Thread producer = new Thread(() -> {
            int num = 0;
            while(true) {
                try {
                    System.out.println("生产了:" + num);
                    queue.put(num);
                    num++;
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();

        Thread customer = new Thread(() -> {
            while(true) {
                try {
                    int num= queue.take();
                    System.out.println("消费了:"+num);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        customer.start();
    }

   /* public static void main1(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        queue.put(1);
        queue.put(2);
        queue.put(3);
        int ret = 0;
        ret = queue.take();
        System.out.println(ret);
        ret = queue.take();
        System.out.println(ret);
        ret = queue.take();
        System.out.println(ret);
    }*/
}
